﻿using System;
using System.IO;

namespace SsrsRenderStudio.Renderer.Output.Version2010
{
    public sealed class FileOutput : Output
    {
        private string _destination;
        private string _fileExt;

        public FileOutput(byte[][] renderReport, string destination, string fileExtension) : base(renderReport)
        {
            _destination = destination;
            _fileExt = fileExtension;
        }

        public override void Process()
        {
            WriteToFile();
        }

        private void WriteToFile()
        {
            try
            {
                for (int i = 0; i < _renderedReport.Length; i++)
                {
                    string filename = _destination + "." + i.ToString() + "." + _fileExt;

                    try { File.Delete(filename); }
                    catch { }

                    // saving as true EMF: http://stackoverflow.com/questions/152729/gdi-c-how-to-save-an-image-as-emf/895204#895204
                    //_metafiles[i].Save(filename);

                    FileStream stream = File.Create(filename, this._renderedReport[i].Length);
                    stream.Write(this._renderedReport[i], 0, this._renderedReport[i].Length);
                    stream.Close();
                }
            }

            catch (Exception e)
            {
                SsrsRenderStudio.Shared.Logger.Log(Shared.EnumLoggingSeverity.ERROR,"****FILE OUTPUT EXCEPTION: " + e.Message);
            }
        }
    }
}
